<template>
  <div class="app-container">
    <el-card>
      <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
      >
        <el-form-item label="施工单位名称">
          <el-input
              v-model="queryParams.name"
              placeholder="请输入施工单位名称"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="addDeviceTypes"
          >新增</el-button
          >
        </el-col>

        <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="postList" stripe border max-height="500">
        <el-table-column label="施工单位名称" align="center" prop="name" />
        <el-table-column label="社会信用代码" align="center" prop="socialCreditCode" />

        <el-table-column label="联系人" align="center" prop="contact"  />

        <el-table-column label="联系电话" align="center" prop="phone" />

        <el-table-column label="联系地址" align="center" show-overflow-tooltip width="500" >
          <template #default="scope">
            <spna>{{scope.row.provinceName}}{{scope.row.cityName}}{{scope.row.countyName}}{{scope.row.address}}
            </spna>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="notes" />

        <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="edit(scope.row)"
            >修改</el-button
            >
            <el-button
                link
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
            >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.page"
          v-model:limit="queryParams.limit"
          @pagination="getList"
      />
    </el-card>
    <el-dialog
        v-model="open"
        :title="title"
        append-to-body
        width="800px"
        v-if="open"
        @close="cancel"
        :close-on-click-modal="false"
    >
      <el-form
          ref="constructionManageRef"
          :model="form"
          :rules="rules"
          label-width="110px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="施工单位名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入施工单位名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="社会信用代码" prop="socialCreditCode">
              <el-input v-model="form.socialCreditCode" placeholder="请输入社会信用代码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系地址" prop="provinceId" style="font-weight: 700">
              <el-select v-model="form.provinceId"  placeholder="选择省" style="width: 200px"  @change="changeProvince">
                <el-option
                    v-for="dict in regionList "
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.areaCode"
                ></el-option>
              </el-select>
              <el-select v-model="form.cityId"  placeholder="选择市" style="width: 200px;margin-left: 10px" @change="changeCity" >
                <el-option
                    v-for="dict in CityList "
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.areaCode"
                ></el-option>
              </el-select>
              <el-select v-model="form.countyId"  placeholder="选择区/县" style="width: 200px;margin-left: 10px" @change="changeCounty" >
                <el-option
                    v-for="dict in countyList "
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.areaCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item  prop="address" style="font-weight: 700">
              <el-input v-model="form.address" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="notes">
              <el-input
                  show-word-limit
                  maxlength="500"
                  v-model="form.notes"
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 8 }"
                  placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormDebounceHandler"
          >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改岗位对话框 -->
  </div>
</template>

<script setup name="constructionManage">

import { region } from '@/api/record/api'

const { proxy } = getCurrentInstance();

import {
  constructionUnit,
  constructionUnitDel,
  constructionUnitSave,
  constructionUnitUpdata
} from '@/api/AgeAppropriate/index'

import { debounce } from "@/utils/debounce.js";

const showSearch = ref(true);
const loading = ref(true);
const postList = ref([]);
const open = ref(false);
const title = ref("新增施工单位");

const total = ref(0);
const regionList=ref([]);
const CityList=ref([]);
const countyList=ref([])

const data = reactive({
  form: {},
  queryParams: {
    page: 1,
    limit: 10,
    name:undefined
  },
  rules: {
    name: [
      { required: true, message: "请输入施工单位名称", trigger: "blur" },
      { required: true, min: 1, max: 50, message: "施工单位不超过50个字符", trigger: "blur" }
    ],
    socialCreditCode: [
      { required: true, message: "请输入社会信用代码", trigger: "blur" },
      { required: true, min:1, max: 50, message: "社会信用代码不超过50个字符", trigger: "blur" }
    ],
    address: [
      { required: false, min: 1, max: 50, message: "详细地址不超过50个字符", trigger: "blur" }
    ],
    contact: [
      { required: true, message: "请输入联系人", trigger: "blur" },
      { required: true, min: 1, max:10, message: "联系人不超过10个字符", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "请输入正确手机号", trigger: "blur"},
      { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
    ],
    provinceId: [
      { required: true, message: "请选择联系地址", trigger: "change" }
    ],
    notes: [
      { required: false, min: 1, max: 50, message: "备注不超过500个字符", trigger: "blur" }
    ]
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 提交按钮 */
/** 提交按钮 */
const submitFormDebounceHandler = debounce(submitForm, 500);
function submitForm() {
  proxy.$refs["constructionManageRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        constructionUnitUpdata(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          reset();
          getList();
        });
      } else {
        constructionUnitSave(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          reset();
          getList();
        });
      }
    }
  });
}
function cancel() {
  open.value = false;
  reset();
}

async function edit(data) {
  form.value = data;
  const data1 = await region(data.provinceId)
  const data2 = await region(data.cityId)
  CityList.value = data1.data
  countyList.value = data2.data
  title.value = "编辑施工单位";
  open.value = true;
}

function reset(){
  proxy.resetForm("constructionManageRef");
  open.value=false;
  form.value={}
}

/** 查询岗位列表 */
function getList() {
  loading.value = true;
  constructionUnit(queryParams.value).then((response) => {
    postList.value = response.page.list;
    total.value = response.page.totalCount;
    loading.value = false;
  });
}
function handleQuery() {
  getList();
}
function resetQuery() {
  queryParams.value = {
    page: 1,
    limit: 10,
    name:undefined
  };
  getList();
}

function handleDelete(row) {
  proxy.$modal
      .confirm("是否确认删除该数据项？")
      .then(function () {
        return constructionUnitDel([row.id]);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(() => {});
}
function addDeviceTypes() {
  title.value = "新增施工单位";
  open.value = true;
}

function getregion(){
  region(0).then(res=>{
    console.log(res)
    regionList.value=res.data
  })
}

function changeProvince(val){
  form.value.provinceName = regionList.value.find(item =>item.areaCode==val)?.name
  CityList.value = []
  form.value.cityId = ''
  form.value.countyId = ''
  countyList.value = []
  region(val).then(res=>{
    CityList.value = res.data
  })

}

function changeCity(val){
  form.value.cityName = CityList.value.find(item=>item.areaCode==val)?.name
  form.value.countyId = ''
  countyList.value = []
  region(val).then(res=>{
    countyList.value=res.data
  })
}

function changeCounty(val){
  form.value.countyName=countyList.value.find(item=>item.areaCode==val)?.name
}

getList();
getregion()
</script>
